
import os, cgi, time, string
import urllib2, logging, base64
from django.utils import simplejson
from google.appengine.ext import webapp  
from google.appengine.ext.webapp import template


class BaseRequestHandler(webapp.RequestHandler):
  """Base template rendering function.
     The get methods of all classes just need to call the
     render_response() method with template variables.  This base class
     finds teh right template path and adds some other used values
  """  
  _OUTPUT_TYPES = {
    'default': ['text/html', 'html'],
    'html': ['text/html', 'html'], 
    'json': ['application/json', 'json'], 
    'atom': ['application/atom+xml', 'xml'],}

  def template_path(self, filename):
    """Returns the full path for a template from its path relative to here."""
    directory = os.path.dirname(__file__) 
    return os.path.join(directory, os.path.join( 'views', filename))
  
  def get_cookie(key_name, default=''):
    """ This will return the value of the cookie with key_name"""
    return self.request.cookies.get(key_name, default)

  def set_cookie(key_name, value=''):
    """ This will set the value of the cookie with key_name""" 
    expire_date = time.time() + 60 * 60 * 24 * 7 * 2 # expire in two weeks
    self.response.headers.add_header('Set-Cookie','%s=%s; expires=' %(key_name, value.encode(), expire_date))

  def render_response(self, filename, template_values={}):
    """Renders a Django template and sends it to the client.
       template_values: argument dict for the template
    """ 
    values ={'current_uri': self.request.uri, 
             'application_name': 'chiefmedicalofficer',
             'flash': cgi.escape(self.request.get('flash')) }
    values.update(template_values)
    
    output_name = template_values.get("output_format", "default")
    output_type = BaseRequestHandler._OUTPUT_TYPES[output_name] 
    # append .html to template if not provided, emable future xml and other template langs
    if len(filename.split(".")) == 1 :
      filename = '%s.%s' %(filename, output_type[1])      
    path = self.template_path(filename) 
    self.response.headers['Content-Type'] = output_type[0]
    if output_type[0] == "json":
        self.response.out.write(values)
    else:    
        self.response.out.write(template.render(path, values, debug= True))
  

  def error_page(self, error, msg=''):
    self.render_response('error.html',{'error': error,'msg': msg})  


